package com.hyundaihds.hdscontacts;

import java.util.*;

import android.app.*;
import android.content.*;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.*;
import android.text.*;
import android.view.*;
import android.widget.*;

public class Menu2 extends ListActivity {
	private String searchKeyword;
	Cursor cursor;

	String str;
	
	
	String d_name = "";
	String d_iaid = "";
	String d_pos_nm = "";
	String d_team_nm = "";
	String d_phone1 = "";
	String d_phone2 = "";
	int d_floor_num = 0;

	// cursor 로 쿼리 검색한 결과 횟수
	int count = 0;
	EditText searchBox;
	SQLiteDatabase db;


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.menu2);

		searchBox = (EditText) findViewById(R.id.EditText01);
		

		db = openOrCreateDatabase("HDSDB.db", MODE_APPEND, null);
		

		ListView lv = getListView();

		try {
			searchBox.addTextChangedListener(new TextWatcher() {

				public void afterTextChanged(Editable arg0) {
					// ignore
				}

				public void beforeTextChanged(CharSequence s, int start,
						int count, int after) {
					
					try {
						searchKeyword = s.toString();
						str = searchKeyword;

						displayList();
					} catch (Exception e) {
					}
					
					
					// ignore
				}

				public void onTextChanged(CharSequence s, int start,
						int before, int count) {
					

					try {
						searchKeyword = s.toString();
						str = searchKeyword;

						displayList();
					} catch (Exception e) {
					}
				}

			});
			
			

			
			displayList();
		} catch (Exception e) {
		}

		lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub

				onListItemClick(arg1, arg2, arg3);

			}

		});

	}

	protected void onListItemClick(View v, int position, long id) {
		
		
		String stt = searchBox.getText().toString();
		int count = 0;
		
		//Toast.makeText(this, stt, Toast.LENGTH_SHORT).show();


		//SQLiteDatabase db;

		db = openOrCreateDatabase("HDSDB.db", MODE_APPEND, null);
//
		cursor = db.rawQuery("SELECT * FROM HDS WHERE NAME LIKE " + "'" + stt+ "%'", null);
		startManagingCursor(cursor);

		while (cursor.moveToNext()) {

			if (count == position) {
				d_name = cursor.getString(2);
				d_iaid = cursor.getString(1);
				d_pos_nm = cursor.getString(5);
				d_team_nm = cursor.getString(4);
				d_phone1 = cursor.getString(6);
				d_phone2 = cursor.getString(7);
				d_floor_num = cursor.getInt(9);

				// ListView 클릭시 다이얼로그 이벤트 발생
				showDialog(count);
				// Toast.makeText(this, cursor.getString(2),
				// Toast.LENGTH_SHORT).show();
				break;
			}
			count++;
		}

		count = 0;

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		super.onCreateDialog(id);

		AlertDialog dlg;

		LayoutInflater layout2 = getLayoutInflater();
		View v2 = layout2.inflate(R.layout.alert_custom_view, null);

		// 다이얼로그 창 내의 TextView
		TextView dltx1 = (TextView) v2.findViewById(R.id.dltxt1);
		TextView dltx2 = (TextView) v2.findViewById(R.id.dltxt2);

		dltx1.setText(d_iaid + "/" + d_team_nm + "/" + d_floor_num + "층");
		dltx2.setText(d_phone1 + "/" + d_phone2);

		// 다이얼로그 창 내의 ImageButton
		ImageButton callBt = (ImageButton) v2.findViewById(R.id.callBt);
		ImageButton txtBt = (ImageButton) v2.findViewById(R.id.txttBt);
		ImageButton seatBt = (ImageButton) v2.findViewById(R.id.seatBt);

		// 전화걸기
		callBt.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				Uri number = Uri.parse("tel:" + d_phone2);
				Intent dial = new Intent(Intent.ACTION_DIAL, number);
				dial.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(dial);

			}
		});

		// 문자보내기
		txtBt.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				/*
				 * Intent i = new Intent(Intent.ACTION_SEND);
				 * i.addCategory(Intent.CATEGORY_DEFAULT);
				 * i.setType("text/plain"); i.putExtra(Intent.EXTRA_SUBJECT,
				 * "EXTRA_SUBJECT"); startActivity(Intent.createChooser(i,
				 * "How do you want to send message?"));
				 */

				Intent i = new Intent(Menu2.this, SmsSender.class);
				startActivity(i);

			}
		});

		// 조직도 보기
		seatBt.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				Intent i = new Intent(Menu2.this, SeatView.class);

				// 층정보 있으니까 DB에서 끌어오면 되고
				i.putExtra("floor", 19); // 층 정보
				// 섹터도 저장해야 한다. DB로 넣거나 array 에는 섹터에 해당되는 좌표
				i.putExtra("sector", 2); // 구역 정보
				startActivity(i);

			}
		});

		dlg = new AlertDialog.Builder(this).setIcon(R.drawable.icon) // icon 지정
				// 후
				// Builder
				// 객체 리턴
				.setTitle(d_name + " " + d_pos_nm) // title 지정
				// .setMessage(str) // 메시지 text 지정

				// AlertDialog의 버튼 생성 & 버튼 클릭 이밴트에 대한 Listener 객체 생성/등록

				// Cancle 버튼 생성
				.setNegativeButton("Cancle",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {

							}
						}).setView(v2).show();
		// 결과로 AlertView return (dlg에 return결과 대입)

		return dlg;
	}

	private List<Contact> getContactsList() throws Exception {

		SQLiteDatabase db;

		db = openOrCreateDatabase("HDSDB.db", MODE_APPEND, null);

		cursor = db.rawQuery("SELECT * FROM HDS", null);
		startManagingCursor(cursor);

		List<Contact> contactsList = new ArrayList<Contact>();

		/*
		 * String[] projection = new String[] { Contacts.People._ID,
		 * Contacts.People.NAME, Contacts.People.NUMBER };
		 * 
		 * Cursor cursor = managedQuery(Contacts.People.CONTENT_URI, projection,
		 * null, null, null);
		 */

		while (cursor.moveToNext()) {
			addContact(contactsList, cursor.getString(2), cursor.getString(7));
		}

		// addContact(contactsList, "Kwon", "01023440477" );
		// addContact(contactsList, "Kim" , "01045453435");
		// addContact(contactsList, "Lee" , "01022342342");
		// addContact(contactsList, "Han" , "01023143445");

		return contactsList;

	}

	private void addContact(List<Contact> contactsList, String name,
			String number) throws Exception {

		if (contactsList == null) {
			throw new NullPointerException("contactList가 null 입니다.");
		}

		boolean isAdd = false;

		if (searchKeyword != null && "".equals(searchKeyword.trim()) == false) {

			String iniName = HangulUtils.getHangulInitialSound(name,
					searchKeyword);

			if (iniName.indexOf(searchKeyword) >= 0) {

				isAdd = true;
			}
		} else {
			isAdd = true;
		}

		if (isAdd) {

			contactsList.add(new Contact(name, number));
		}
	}

	private class ContactsListAdapter<T extends Contact> extends
			ArrayAdapter<T> {

		private List<T> contactsList;

		public ContactsListAdapter(Context context, int textViewResourceId,
				List<T> items) {
			super(context, textViewResourceId, items);
			contactsList = items;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = convertView;
			if (view == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				view = vi.inflate(R.layout.menu2_row, null);
			}

			T contacts = contactsList.get(position);
			if (contacts != null) {
				TextView viewName = (TextView) view.findViewById(R.id.toptext);
				if (viewName != null) {
					viewName.setText(contacts.getName());
				}

				TextView viewNumber = (TextView) view
						.findViewById(R.id.bottomtext);
				if (viewNumber != null) {
					viewNumber.setText("전화번호 : " + contacts.getNumber());
				}
			}

			return view;
		}

	}

	private void displayList() throws Exception {

		List<Contact> contactsList = null;
		contactsList = getContactsList();
		ContactsListAdapter<Contact> adapter = new ContactsListAdapter<Contact>(
				this, R.layout.menu2_row, contactsList);
		setListAdapter(adapter);
	}

}